package tako.wisers.com.android.apis.activity;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.json.JSONObject;

import tako.wisers.com.android.apis.R;
import tako.wisers.com.android.apis.http.HttpGeter;
import tako.wisers.com.android.apis.util.Global;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class LuckyDrawResultActivity extends Activity {
	private Dialog mDialog;
	private static final String PRIZE_MASSAGE = "抽奖中...";
	private static final int SUCCESS = 0;
	private static final int FAILER = 1;
	private int mPrizeLevel;
	private static final String URL = "http://hylabfour.appspot.com/lackyservice?Lat=%f&Long=%f&level=%d";
	private static final float PICTURE_MAX_SIZE = 307200f;
	private double mLat;
	private double mLnt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lucky_draw_result);

		mDialog = ProgressDialog.show(this, "", PRIZE_MASSAGE, true, false);
		Intent intent = getIntent(); 
		
		mLat = intent.getDoubleExtra(Global.LATITUDE_E6_EXTRA, -1);
		mLnt = intent.getDoubleExtra(Global.LONGITUDE_E6_EXTRA, -1);

		findViewById(R.id.lucky_button).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
				startActivityForResult(i, Activity.DEFAULT_KEYS_DIALER);
			}
			
		});
		
		new RollThread().start();
		
		System.gc();
	}
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			mDialog.dismiss();
			switch (msg.what) {
			case SUCCESS:
				String text = "恭喜您中了" + (mPrizeLevel +1) + "等奖,请按下面的按键并拍下刚才所选地点的照片";
				((TextView)findViewById(R.id.lucky_msg)).setText(text);
				findViewById(R.id.lucky_button).setVisibility(View.VISIBLE);
				break;
			case FAILER:
				((TextView)findViewById(R.id.lucky_msg)).setText("谢谢参与");
				break;
			}
		}
	};

	class RollThread extends Thread {
		@Override
		public void run() {
			HttpURLConnection conn;
			try {
				HttpGeter geter = new HttpGeter("http://hylabfour.appspot.com/lackyservice?pwd=123");
				String content = geter.getContent();
				JSONObject result = new JSONObject(content);
				Integer level = result.getInt("level");
				System.gc();
				if (level == null || level == -1) {
					mHandler.sendMessage(mHandler.obtainMessage(FAILER));
					return;
				}
				mPrizeLevel = level;
				mHandler.sendMessage(mHandler.obtainMessage(SUCCESS));
			} catch (Exception e) {
				e.printStackTrace();
				mHandler.sendMessage(mHandler.obtainMessage(FAILER));
			} 
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Bundle extras = data.getExtras();
		Bitmap b = (Bitmap) extras.get("data");

		if (b != null) {
			Dialog dialog = new AlertDialog.Builder(this).setIcon(
					R.drawable.alert_dialog_icon).setNegativeButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							LuckyDrawResultActivity.this.finish();
						}
					}).create();
			try {
				uploadBitmap(b, data);
				dialog.setTitle("传送完成");
			} catch (Exception e) {
				e.printStackTrace();
				dialog.setTitle("传送失败");
			}
			dialog.show();
		}

	}

	private void uploadBitmap(Bitmap b, Intent data) throws IOException,
			MalformedURLException, ProtocolException {
		String url = String.format(URL, mLat, mLnt, mPrizeLevel);
		HttpURLConnection conn = (HttpURLConnection) new URL(url)
				.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("PUT");
		DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		b.compress(CompressFormat.PNG, 100, baos);
		int size = baos.size();
		if (PICTURE_MAX_SIZE < size) {
			baos.close();
			baos = null;
			System.gc();
			baos = new ByteArrayOutputStream();
			int qurytly =  Math.round(PICTURE_MAX_SIZE * 100/ size);
			if(qurytly == 0) qurytly = 1;
			b.compress(CompressFormat.PNG, qurytly,	baos);
		}
		byte[] bytes = baos.toByteArray();
		dos.write(bytes);
		InputStream is = conn.getInputStream();
		IOUtils.toString(is);
		baos.close();
		dos.flush();
		dos.close();
		is.close();
		conn.disconnect();
	}

}
